package com.shengdacar.sharelibrary.utils;

import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.text.TextUtils;

import com.shengdacar.sharelibrary.callback.AsyncCallBack;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * 作者：huyi
 * 日期：2020/12/17 10:45
 * 描述：
 */
public class BitmapSaveAsyncTask{
    private final String path;
    private final String name;
    private final AsyncCallBack asyncCallBack;
    public BitmapSaveAsyncTask(String path, String name ,AsyncCallBack asyncCallBack) {
        this.path = path;
        this.name = name;
        this.asyncCallBack = asyncCallBack;
    }

    public void execute(Bitmap bitmap){
        PictureThreadUtils.executeByIo(new PictureThreadUtils.SimpleTask<File>() {
            @Override
            public File doInBackground() throws Throwable {
                File f = new File(path, name);
                if (f.exists()) {
                    f.delete();
                }
                try {
                    FileOutputStream out = new FileOutputStream(f);
                    bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
                    out.flush();
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                return f;
            }

            @Override
            public void onSuccess(File file) {
                if (file == null) {
                    return;
                }
                if (asyncCallBack != null) {
                    asyncCallBack.fileBack(file);
                }
            }
        });
    }
}
